import axios from 'axios'
import store from '../store'
import {getToken} from './auth'
import Config from "@/config/Config";
import qs from 'qs'
import {isEmpty} from "@/utils/helpers";
// create an axios instance
const service = axios.create({
    baseURL: Config.apiName, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000, // request timeout
    paramsSerializer(data: any) {
        return qs.stringify(data, {arrayFormat: 'indices'})
    },
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "X-Requested-With": "XMLHttpRequest"
    },
})

// request interceptor
service.interceptors.request.use(
    (config: any) => {
        // do something before request is sent
        const token = getToken()
        if (token && config.url.indexOf('/remote/login') === -1) {
            config.headers['token'] = token
        }
        store.commit('app/changeLoading', true)
        if (!isEmpty(config.data)) {
            const ContentType = config.headers['Content-Type'] || ''
            if (ContentType.indexOf('application/json') >= 0) {
                config.data = JSON.stringify(config.data)
            } else if (!(config.data instanceof FormData)) {
                config.data = qs.stringify(config.data)
            }
        }
        return config
    },
    (error: any) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (response: any) => {
        const status = response.status
        const res = response.data

        // if the custom code is not 20000, it is judged as an error.
        if (status !== 200) {
            store.commit('app/changeLoading', false)
            return Promise.reject(new Error(res.message || 'Error'))
        }
        if (response.headers.token) {
            // setToken(response.headers.token)
        }
        if (!res.result) {
            store.commit('app/changeLoading', false)
            return Promise.reject(new Error(res.message || 'Error'))
        }
        store.commit('app/changeLoading', false)

        return res
    },
    (error: any) => {
        store.commit('app/changeLoading', false)
        return Promise.reject(error)
    }
)
export default service
